<template>
  <div class="player-wrap">
    <template v-if="rtcStream">
      <video :srcObject.prop="rtcStream" autoplay muted controls></video>
    </template>
  </div>
</template>

<script>
  import {getWebRtcRemoteSdp} from "../../api/api";

  export default {
    name: "WebrtcPlayer",
    rtcPeerConnection: null,
    data() {
      return {
        iceConnectionState: '',
        rtcPeerConnectionInit: false,
        rtcStream: null
      }
    },
    props: {
      streamPath: {
        type: String,
        default: ''
      }
    },
    watch: {
      'streamPath': function (newValue, oldValue) {

      }
    },
    async created() {
      await this.initRtcPeerConnection();
      console.log('initRtcPeerConnectioned');
      if (this.streamPath) {
        await this.play(this.streamPath);
        console.log('played');
      }
    },
    methods: {
      async initRtcPeerConnection() {
        const rtcPeerConnection = new RTCPeerConnection();

        rtcPeerConnection.addTransceiver('video', {
          direction: "recvonly"
        });

        rtcPeerConnection.onsignalingstatechange = e => {
          console.log('onsignalingstatechange', e);
        };

        rtcPeerConnection.oniceconnectionstatechange = e => {
          console.log('oniceconnectionstatechange', rtcPeerConnection.iceConnectionState);
        };

        rtcPeerConnection.onicecandidate = event => {
          console.log('onicecandidate', event);
        };

        rtcPeerConnection.ontrack = event => {
          console.log('ontrack', event);
          if (event.track.kind === "video") {
            this.rtcStream = event.streams[0];
          }
        };

        const rtcSessionDescriptionInit = await rtcPeerConnection.createOffer();
        await rtcPeerConnection.setLocalDescription(rtcSessionDescriptionInit);
        this.rtcPeerConnectionInit = true;
        this.$options.rtcPeerConnection = rtcPeerConnection;
      },

      //
      async play(streamPath) {
        const rtcPeerConnection = this.$options.rtcPeerConnection;
        const localDescriptionData = rtcPeerConnection.localDescription.toJSON();
        const result = await getWebRtcRemoteSdp(streamPath, localDescriptionData);
        if (result.error) {
          return;
        }
        //
        rtcPeerConnection.setRemoteDescription(new RTCSessionDescription({
          type: result.type,
          sdp: result.sdp
        }));
      },
      close() {
        const rtcPeerConnection = this.$options.rtcPeerConnection;
        rtcPeerConnection && rtcPeerConnection.close();
      }
    },
    destroyed() {
      this.close();
    }
  }
</script>

<style lang="scss" scoped>

  .player-wrap {
    width: 100%;
    height: 100%;

    video {
      width: 100%;
      height: 100%;
    }
  }
</style>
